package com.example.tx;

import java.net.InetSocketAddress;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;


public class UdpClientHandler extends SimpleChannelInboundHandler<DatagramPacket> {
    private static JsonUtil utils = new JsonUtil();//工具类


    private String OWN_IP =null;
    //打印日志
//    public static final Logger log = Logger.getLogger(UdpClientHandler.class);
    //在事件循环中执行
//    private EventExecutor executor;

    //客户端与服务器端连接成功的时候触发
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
//        log.info("UDP通道已经连接");
        System.out.println("UDP通道已经连接");
        super.channelActive(ctx);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet)
            throws Exception {
        // 读取收到的数据
        ByteBuf buf = (ByteBuf) packet.copy().content();
        byte[] req = new byte[buf.readableBytes()];

        buf.readBytes(req);
        String body = new String(req, CharsetUtil.UTF_8);
//        Address address = utils.fromJson(body, Address.class);
        System.out.println("收到的消息为" + body);
        try {
            if (body.contains("Server")) {
                Address message = utils.fromJson(body, Address.class);
                OWN_IP = message.getMess();
                System.out.println("server:"+OWN_IP);
            }
            if (body.contains("True")) {
                Address message = utils.fromJson(body, Address.class);
                String mess = message.getMess();
                System.out.println("true:" +mess);

                System.out.println("进来了");
                String[] split = mess.split(":");
                System.out.println("ip"+split[0].replace("/", "")+"端口"+Integer.parseInt(split[1]));
                //发一次可能无效，需要多发几次 定义发送5次
                for (int i=0;i<5;i++){
                    ctx.writeAndFlush(new DatagramPacket(
                            Unpooled.copiedBuffer("你好" +
                                    "", CharsetUtil.UTF_8),
                            //地址
                            new InetSocketAddress(
                                    split[0].replace("/", ""), Integer.parseInt(split[1])
                            )));
                }
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }
    //消息没有结束的时候触发
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    //捕获异常
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //logger.log(Level.INFO, "AuthServerInitHandler exceptionCaught");
//        log.error("UdpServerHandler exceptionCaught" + cause.getMessage());
        System.out.println("UdpServerHandler exceptionCaught" + cause.getMessage());
        cause.printStackTrace();
        ctx.close();
    }
}

